import { baseURL }  from '../config/api-config'
import { getStorageExpire } from '../plugins/utils'

// H5版本
// #ifdef H5
import Fly from 'flyio/dist/npm/fly'
// #endif

//微信小程序和APP版本
// #ifndef H5
import Fly from 'flyio/dist/npm/wx'
// #endif

const request = new Fly();

/*
******* 请求拦截 *******
*/ 
request.interceptors.request.use((request) => {

  request.baseURL = baseURL;
  const token = getStorageExpire('access_token');
  // headers添加token
  if (token) {
    request.headers["Authorization"] = "bearer " + token;
  }
  // 防止缓存
  if (request.method === 'POST' && request.headers['Content-Type'] !== 'multipart/form-data') {
    request.body = {
      ...request.body,
      _t: Date.parse(new Date()) / 1000
    }
  } else if (request.method === 'GET') {
    request.params = {
      _t: Date.parse(new Date()) / 1000,
      ...request.params
    }
  }
  return request
})

/*
******* 响应拦截 *******
*/ 
request.interceptors.response.use(function(response) { //不要使用箭头函数，否则调用this.lock()时，this指向不对 
  const data = response.data;
  if (!data || typeof data !== 'object') {
    uni.showToast({
      title: '服务器响应错误，请重试',
      icon: 'none'
    })
  } 
  return response.data; //只返回业务数据部分
}, function(err) {
  const { response: { data } } = err;
  if(err.status === 401){
	  if(data.error === 'invalid_token'){
		  uni.clearStorageSync('access_token');
		  uni.reLaunch({
		  	url: '/pages/home/index'
		  })
	  }else{
		  uni.showToast({
		    title: data.error,
		    icon: 'none'
		  })
	  }
  }else if(err.status === 500){
	  uni.showToast({
	    title: '服务器未知错误，请重试',
	    icon: 'none'
	  })
  }
})

export default request
